package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired(required = false)
    private ShoppingCartService shoppingCartService;


    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        //1.获取当前登录的对象
        Long userId = (Long) session.getAttribute("user");

        //2.给购物车指定所属用户
        shoppingCart.setUserId(userId);

        //3.调用处理层方法
        R<ShoppingCart> result = shoppingCartService.add(shoppingCart);

        //4.返回结果，
        return result;
    }

    @GetMapping("/list")
    public R<List<ShoppingCart>> list(HttpSession session){
        //1.获取当前登录的用户
        Long userId = (Long) session.getAttribute("user");

        //2.查看当前用户的购物车信息
        R<List<ShoppingCart>> result = shoppingCartService.findCartByUserId(userId);
        return result;
    }


    @DeleteMapping("/clean")
    public R<String> clean(HttpSession session){
        //1.获取登录的用户
        Long userId = (Long) session.getAttribute("user");
        //2.根据id查找购物车，并清空
        shoppingCartService.cleanCart(userId);
        return R.success("清空购物车成功");
    }

    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart ,HttpSession session){
        //1.获取登录用户
        Long userId = (Long) session.getAttribute("user");
        //2.根据dishId查找购物项并删除
        shoppingCart.setUserId(userId);
        R<ShoppingCart> result =shoppingCartService.delect(shoppingCart);
        return result;
    }

}
